package com.rawchen.controller;

import com.rawchen.domain.User;
import com.rawchen.service.UserService;
import com.rawchen.utils.GravatarUtil;
import com.rawchen.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Objects;

/**
 *
 *
 *
 * 采用第三方SDK的方式进行操作
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @Resource
    protected UserService userService;




    /**
     * 开放平台微信登录
     * @param returnUrl
     * @return
     */
    @GetMapping("/qrAuthorize")
    public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) throws Exception {
        String url = "http://www.pinzhi365.com/wechat/qrUserInfo";
        String redirectUrl = wxMpService.buildQrConnectUrl(url, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl, "UTF-8"));
        return "redirect:" + redirectUrl;
    }

    /**
     * 用户授权后，微信服务器回调url
     * 开放平台微信登录，获取用户的openId
     * @param code
     * @param returnUrl
     * @return
     */
    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code,
                             @RequestParam("state") String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxuser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            // 得到用户信息，如果表中不存在就插入
            String nickname = wxuser.getNickname();
            String openId = wxuser.getOpenId();

            // 判断如果用户是绑定的，就不新增，若没绑定，新增一个用户
            User user1 = userService.selectUserByOpenId(openId);
            if(Objects.isNull(user1)){
                String headImgUrl = wxuser.getHeadImgUrl();
                User user=new User();
                user.setName(nickname);
                user.setPassword(null);
                user.setCreated(new Date());
                user.setScreenname(nickname);
                user.setActivated(new Date());
                user.setRole("user");
                user.setPhoto(headImgUrl);
                user.setOpenid(StringUtil.passwordToMd5(openId));
                userService.insert(user);
                // TODO 如果用户新增失败，要进行判断
            }
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new RuntimeException(e.getError().getErrorMsg());
        }
        log.info("wxMpOAuth2AccessToken={}", wxMpOAuth2AccessToken);
        String openId = wxMpOAuth2AccessToken.getOpenId();

        return "redirect:" + returnUrl + "?openid=" + openId;
    }
}
